package contegor.scire.structure.lang;

import static contegor.scire.structure.Constants.ORDER;

import java.util.Comparator;

import contegor.scire.core.Id;
import contegor.scire.core.Link;
import contegor.scire.structure.Constants;

/**
 * This {@link Comparator} allows to sort {@link Link}s that have {@link Constants#ORDER} definition.
 * 
 * @author  Héctor Cirbián Pousa
 */
public class OrderedLinksComparator implements Comparator<Link> {
  @Override
  public int compare(Link o1, Link o2) {
    Id order1 = null;
    Id order2 = null;
    for (Link link: o1.getLinks().values())
      if (link.isLinkedWith(ORDER))
        order1 = link.getTarget();
    for (Link link: o2.getLinks().values())
      if (link.isLinkedWith(ORDER))
        order2 = link.getTarget();
    if ((order1 == null) || (order2 == null))
      throw new IllegalArgumentException(o1.getSource() + " meaning Links need to be ordered, but they are not.");
    return order1.getLastIdFragment().compareTo(order2.getLastIdFragment());
  }
}